<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use App\Models\CrawlerPictuer;
use App\Handlers\DownLoadPictuerHandler;
use App\Models\Pictuer;
use App\Models\Tag;

class CrawlerPictuerJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $pictuer;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(CrawlerPictuer $pictuer)
    {
        $this->pictuer = $pictuer;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if($this->pictuer->download_count >= 4) {
            // 图片最多尝试下载 4 次，超过4次跳过抓取
            \DB::table('crawler_pictuers')->where('id', $this->pictuer->id)->update([
                'crawler' => 1
            ]);
            return ;
        }
        // 每次尝试抓取 记录次数
        $this->pictuer->increment('download_count');
        // 通过图片下载处理器 处理要抓取得源地址
        $result = app(DownLoadPictuerHandler::class)->upload($this->pictuer->origin);
        // 有图片信息返回
        if ($result) {
            // 图片采集完成，加入主图片库
            $result['article_id'] = 0;
            $result['crawler_pictuer_id'] = $this->pictuer->id;
            $result['category_id'] = $this->pictuer->category_id;
            $result['user_id'] = 1;
            $result['ext'] = str_replace('image/', '', $result['mime']);
            // 先处理标签
            // 处理标签信息
            $tags = $this->pictuer->tags;
            $tag = new Tag;
            $tag_array = $tag->createByName($tags);
            // 检查图片是否存在
            $pictuer_model = new Pictuer;
            $pic = Pictuer::firstOrcreate(['md5' => $result['md5']], $result);

            // 更新关联
            $pic->tags()->syncWithoutDetaching($tag_array);
            // 更新图片采集信息
            \DB::connection('crawler-mysql')->table('crawler_pictuers')->where('id', $this->pictuer->id)->update([
                'oss' => $result['path'] . '/' . $result['filename'],
                'crawler' => 1,
                'pictuer_id' => $pic->id
            ]);
        }
    }
}
